package td3.model;

import javax.swing.tree.DefaultMutableTreeNode;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ContactHandler extends DefaultHandler {

	DefaultMutableTreeNode root;
	DefaultMutableTreeNode current;
	ContactTreeModel contacts = null;
	String tempVal;
	boolean inContact = false;

	public ContactHandler(ContactTreeModel contacts) {
		this.contacts = contacts;
	}

	public ContactTreeModel getContactTreeModel() {
		return contacts;
	}

	@Override
	public void startDocument() throws SAXException {
		root = new DefaultMutableTreeNode("Contacts");
		current = root;
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		tempVal = "";
		if (qName.equalsIgnoreCase("contact")) {
			inContact = true;
			Contact tempContact = new Contact();
			DefaultMutableTreeNode tempNode = new DefaultMutableTreeNode(
					tempContact);
			current.add(tempNode);
			current = tempNode;
		} else if (!qName.equalsIgnoreCase("nom")
				&& !qName.equalsIgnoreCase("mail")
				&& !qName.equalsIgnoreCase("icone")) {
			DefaultMutableTreeNode tempNode = new DefaultMutableTreeNode();
			current.add(tempNode);
			current = tempNode;
		}

	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		tempVal = new String(ch, start, length);
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (inContact) {
			Contact currentContact = (Contact) current.getUserObject();
			if (qName.equalsIgnoreCase("contact")) {
				DefaultMutableTreeNode parent = (DefaultMutableTreeNode) current
						.getParent();
				current = parent;
				inContact = false;
			} else if (qName.equalsIgnoreCase("nom")) {
				currentContact.setNom(tempVal);
			} else if (qName.equalsIgnoreCase("mail")) {
				currentContact.setMail(tempVal);
			} else if (qName.equalsIgnoreCase("icone")) {
				currentContact.setIcone(tempVal);
			}
		} else {
			current.setUserObject(new String(qName));
			DefaultMutableTreeNode parent = (DefaultMutableTreeNode) current
					.getParent();
			current = parent;
		}
	}

	@Override
	public void endDocument() throws SAXException {
		contacts.setRoot(root);
	}
}
